using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using TPOJ.BLL;
using System.Data.Entity;
using TPOJ.Web.ViewModel;
using TPOJ.Model;

namespace TPOJ.Web.Controllers
{
    public class ProblemController : Controller
    {
        //
        // GET: /Problem/

        public ActionResult Index(int id)
        {
            if (User.Identity.IsAuthenticated)
            {
                AccountBO accountBO = new AccountBO();
                int userId = accountBO.GetAccountByName(User.Identity.Name).UniqueId;
                ViewData["TriedIds"] = SolutionDataProxy.GetTriedNotACedProblemIdsByUser(userId);
                ViewData["SolvedIds"] = SolutionDataProxy.GetSolvedProblemIdsByUser(userId);
            }
            ViewData.Model = ProblemDataProxy.GetProblemsByVolume(id);
            ViewData["VolumeId"] = id;
            return View();
        }

        public ActionResult Details(int id, int? contestId)
        {
            var currentContests = ContestDataProxy.GetCurrentContests();
            var query = from c in currentContests
                        where c.Problems.Select(p => p.UniqueID).Contains(id)
                        select c;
            var contestsList = query.ToList();
            var result = new List<Contest>();

            if (contestId != null && contestsList.Count>0)
            {
                var findCurrent = from c in contestsList
                                  where c.UniqueID == contestId
                                  select c;
                result.Add(findCurrent.First());
            }
            else
            {
                result = contestsList;
            }

            if (result.Count > 0)
                ViewData["inContest"] = true;
            else
                ViewData["inContest"] = false;
            ViewData["CurrentContests"] = result;
            ViewData["ContestId"] = contestId ?? 0;
            ViewData.Model = ProblemDataProxy.GetProblem(id);
            return View();
        }

        public ActionResult Status(int? id)
        {
            int pid = id ?? 1000;
            ViewData["problemId"] = pid;
            //Do statistics
            var solutions = SolutionDataProxy.GetProblemSolutions(pid);

            StatisticsRecord record = new StatisticsRecord((IList<Core.Language>)this.HttpContext.Application["languages"]);
            record.ProblemId = pid;

            var solsByResult = solutions.GroupBy(s => s.Result);
            foreach (var sol in solsByResult)
            {
                byte result = sol.Key;
                record.ResultsCount[result] = sol.Count();
            }

            var solsByLang = solutions.GroupBy(s => s.Language);
            foreach (var sol in solsByLang)
            {
                string lang = sol.Key;
                record.LanguagesCount[lang] = sol.Count();
            }

            var solsByUser = solutions.GroupBy(s => s.AccountID);
            record.UserCountSubmitted = solsByUser.Count();

            var bestSolutions = from s in solutions
                                where s.Result == 13//magic number here for AC
                                orderby s.Time, s.Memory, s.CodeLength
                                select s;
            ViewData.Model = bestSolutions.ToList();

            var bestSolsByUser = bestSolutions.GroupBy(s => s.AccountID);
            record.UserCountSolved = bestSolsByUser.Count();

            ViewData["Statistics"] = record;
            return View();
        }

        [Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
            ViewData.Model = new Problem { TimeLimit = 1000, MemoryLimit = 10000 };
            return View();
        }

        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult Create(Problem problem)
        {
            problem.Date = DateTime.Now;
            ProblemBO problemBO = new ProblemBO();
            problemBO.Create(problem);
            return RedirectToAction("Index", "Problem", new { id = 1 });
        }

        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id)
        {
            ViewData.Model = ProblemDataProxy.GetProblem(id);
            return View();
        }

        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult Edit(Problem problem)
        {
            ProblemBO problemBO = new ProblemBO();
            problemBO.Edit(problem);
            return RedirectToAction("Index", "Problem", new { id = 1 });
        }
    }
}
